import xbmcplugin, xbmcaddon
import hockeystreams, utils
import os
import datetime

# xbmc-hockey-streams
# author: craig mcnicholas
# contact: craig@designdotworks.co.uk

# Method to draw the home screen
def HOME():
    print 'HOME()'
    utils.addDir('Archives', utils.Mode.ARCHIVES, '', None)

# Method to draw the archives screen
def ARCHIVES():
    print 'ARCHIVES()'
    utils.addDir('By Date', utils.Mode.ARCHIVES_BY_DATE, '', None)

# Method to draw the archives by date screen
# which scrapes the external source and presents
# a list of years for archives
def ARCHIVES_BY_DATE():
    print 'ARCHIVES_BY_DATE()'

    # Retrieve the available dates
    dates = hockeystreams.availableDates(None, None)

    # Find unique years
    years = []
    for date in dates:
        if years.count(date.year) < 1:
            years.append(date.year)

    # Add directories for years
    for year in years:
        params = {
            'year': str(year)
        }
        utils.addDir(str(year), utils.Mode.ARCHIVES_BY_DATE_YEAR, '', params)

# Method to draw the archives by date screen
# which scrapes the external source and presents
# a list of months for a given year of archives
# @param year the year to obtain valid months for
def ARCHIVES_BY_DATE_YEAR(year):
    print 'ARCHIVES_BY_DATE_YEAR(year)'
    print 'Year: ' + str(year)

    # Retrieve the available dates
    dates = hockeystreams.availableDates(None, None)

    # Find unique months
    months = []
    for date in dates:
        if year == date.year and months.count(date.month) < 1:
            months.append(date.month)

    # Add directories for months
    for month in months:
        # Create datetime for string formatting
        date = datetime.date(year, month, 1)
        params = {
            'year': str(year),
            'month': str(month)
        }
        utils.addDir(date.strftime('%B %Y'), utils.Mode.ARCHIVES_BY_DATE_MONTH, '', params)

# Method to draw the archives by date screen
# which scrapes the external source and presents
# a list of days for a given year and month of archives
# @param year the year to obtain valid months for
# @param month the month to obtain valid days for
def ARCHIVES_BY_DATE_MONTH(year, month):
    print 'ARCHIVES_BY_DATE_MONTH(year, month)'
    print 'Year: ' + str(year)
    print 'Month: ' + str(month)

    # Retrieve the available dates
    dates = hockeystreams.availableDates(None, None)

    # Find unique days
    days = []
    for date in dates:
        if year == date.year and month == date.month and days.count(date.day) < 1:
            days.append(date.day)

    # Add directories for days
    for day in days:
        # Create datetime for string formatting
        date = datetime.date(year, month, day)
        params = {
            'year': str(year),
            'month': str(month),
            'day': str(day)
        }
        utils.addDir(date.strftime('%A %d %B %Y'), utils.Mode.ARCHIVES_BY_DATE_DAY, '', params)

# Method to draw the archives by date screen
# which scrapes the external source and presents
# a list of archived games for a given day
# @param username the username to login with
# @param password the password to login with
# @param year the year to obtain valid months for
# @param month the month to obtain valid days for
# @param day the day to obtain valid games for
def ARCHIVES_BY_DATE_DAY(username, password, year, month, day):
    print 'ARCHIVES_BY_DATE_DAY(year, month, day)'
    print 'Year: ' + str(year)
    print 'Month: ' + str(month)
    print 'Day: ' + str(day)

    # Retrieve the events
    date = datetime.date(year, month, day)
    events = hockeystreams.events(None, None, date)

    # Perform login
    token = hockeystreams.login(username, password)

    # Add directories for events
    for event in events:
        streamUrl = hockeystreams.eventStream(username, token, event)
        if streamUrl != None:
            utils.addLink(event.awayTeam + ' @ ' + event.homeTeam, streamUrl, '')

# deals with a bug where errors are thrown 
# if data directory does not exist.
addonId = 'plugin.video.xbmc-hockey-streams'
dataPath = 'special://profile/addon_data/' + addonId
if not os.path.exists: os.makedirs(dataPath)
settings = xbmcaddon.Addon(id = addonId)
	
# Load settings
username = settings.getSetting('username')
password = settings.getSetting('password')

# Load the parameters
params = utils.getParams()

# Print params for debugging
for k, v in params.iteritems():
    print k + ': ' + v

# Attempt to parse mode
mode = utils.parseParamInt(params, 'mode')

# Attempt to parse other variables
url = utils.parseParamString(params, 'url')
year = utils.parseParamInt(params, 'year')
month = utils.parseParamInt(params, 'month')
day = utils.parseParamInt(params, 'day')

# Find mode and execute
if mode == None or mode == utils.Mode.HOME:
    HOME()
elif mode == utils.Mode.ARCHIVES:
    ARCHIVES()
elif mode == utils.Mode.ARCHIVES_BY_DATE:
    ARCHIVES_BY_DATE()
elif mode == utils.Mode.ARCHIVES_BY_DATE_YEAR:
    ARCHIVES_BY_DATE_YEAR(year)
elif mode == utils.Mode.ARCHIVES_BY_DATE_MONTH:
    ARCHIVES_BY_DATE_MONTH(year, month)
elif mode == utils.Mode.ARCHIVES_BY_DATE_DAY:
    ARCHIVES_BY_DATE_DAY(username, password, year, month, day)

xbmcplugin.endOfDirectory(int(sys.argv[1]))
